<template>
  <div class="login-container">
    <van-nav-bar title="用户登录" />
    
    <van-form @submit="onSubmit" class="login-form">
      <van-cell-group inset>
        <van-field
          v-model="form.username"
          name="username"
          label="用户名"
          placeholder="请输入用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
          clearable
        />
        <van-field
          v-model="form.password"
          type="password"
          name="password"
          label="密码"
          placeholder="请输入密码"
          :rules="[{ required: true, message: '请填写密码' }]"
          clearable
        />
      </van-cell-group>

      <div class="action-area">
        <van-button 
          round 
          block 
          type="primary" 
          native-type="submit"
          :loading="loading"
          loading-text="登录中..."
        >
          登录
        </van-button>
        
        <div class="test-account-hint">
          <p>测试账号: <strong>user123</strong></p>
          <p>测试密码: <strong>user123</strong></p>
        </div>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { login } from '@/api/auth'
import { useUserStore } from '@/stores/user'
import { showToast } from 'vant'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const form = ref({
  username: 'user123',  // 默认测试账号
  password: 'user123'   // 默认测试密码
})

const loading = ref(false)

const onSubmit = async () => {
  loading.value = true;
  try {
    const res = await login({
      username: form.value.username,
      password: form.value.password
    });
    
    if (res.errno === 0) {
      userStore.setUser({
        token: res.data.token,
        username: "user123", 
        userInfo: res.data.userInfo || {}
      });
      
      showToast('登录成功');
      router.replace(route.query.redirect || '/mine'); 
    }
  } finally {
    loading.value = false;
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  background-color: #f7f8fa;
    min-width: 78vh;
}

.login-form {
  margin-top: 20px;
}

.action-area {
  padding: 16px;
}

.test-account-hint {
  margin-top: 20px;
  padding: 12px;
  background-color: #f5f5f5;
  border-radius: 8px;
  font-size: 14px;
  color: #666;
  text-align: center;
}

.test-account-hint strong {
  color: #ee0a24;
}
</style>